﻿using AutoMapper;
using B.S.Meeting.Domain;
using B.S.Meeting.ErrorCode;
using B.S.Meeting.Infrastructure.Interfaces;
using B.S.Meeting.ReadAPI.Applications.Commands.Users;
using B.S.Meeting.ReadAPI.Dtos;
using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Numerics;
using System.Security.Claims;
using System.Text;
using Yitter.IdGenerator;

namespace B.S.Meeting.ReadAPI.Applications.CommandHandlers.Users
{
    public class LoginCommandHandler : IRequestHandler<LoginCommand, APIResult<UserDto>>
    {
        IConfiguration configuration;
        IBaseRepository<User> uRep;
        IMapper mapper;
        ILogger<LoginCommandHandler> logger;

        public LoginCommandHandler(IBaseRepository<User> uRep, IMapper mapper, ILogger<LoginCommandHandler> logger, IConfiguration configuration)
        {
            this.uRep = uRep;
            this.mapper = mapper;
            this.logger = logger;
            this.configuration = configuration;
        }

        public async Task<APIResult<UserDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (request.UserPhone != null)
                {
                    var phone = await uRep.GetAsync(x => x.UserPhone == request.UserPhone && x.IsDel == false);
                    if (phone == null)
                    {
                        return new APIResult<UserDto>
                        {
                            Code = StatusEnumCode.Fail,
                            Message = "手机号不存在",
                            Data = null
                        };
                    }
                    
                    if (phone.UserPwd == request.UserPwd.GetMD5())
                    {

                        var userDto = mapper.Map<UserDto>(phone);
                        // 生成JWT令牌
                        userDto.Token = GenerateJwtToken(userDto);
                        return new APIResult<UserDto>
                        {
                            Code = StatusEnumCode.Ok,
                            Message = "登录成功",
                            Data = userDto
                        };
                    }
                }
                else
                {
                    var name = await uRep.GetAsync(x => x.UserName == request.UserName && x.IsDel == false);
                    if (name == null)
                    {
                        return new APIResult<UserDto>
                        {
                            Code = StatusEnumCode.Fail,
                            Message = "用户名不存在",
                            Data = null
                        };
                    }
                   
                    if (name.UserPwd == request.UserPwd.GetMD5())
                    {
                        var userDto = mapper.Map<UserDto>(name);
                        // 生成JWT令牌
                        userDto.Token = GenerateJwtToken(userDto);
                        return new APIResult<UserDto>
                        {
                            Code = StatusEnumCode.Ok,
                            Message = "登录成功",
                            Data = userDto
                        };
                    }
                }
                
                return new APIResult<UserDto>
                {
                    Code = StatusEnumCode.Fail,
                    Message = "密码错误",
                    Data = null
                };
            }
            catch (Exception ex)
            {
                logger.LogError("登录出错", ex.Message);
                throw;
            }
        }


        /// <summary>
        /// 生成JWT令牌
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public string GenerateJwtToken(UserDto user)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JwtSettings:SecretKey"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var claims = new[]
            {
           new Claim("UserName", user.UserName),
           new Claim("UserId", user.UserId.ToString()),
           //new Claim("RoleId", user.RoleId.ToString()),
           //new Claim("RoleName", user.RoleName)
       };

            var token = new JwtSecurityToken(
                issuer: configuration["JwtSettings:Issuer"],
                audience: configuration["JwtSettings:Audience"],
                claims: claims,
                expires: DateTime.Now.AddMinutes(120),
                signingCredentials: credentials
            );

            return new JwtSecurityTokenHandler().WriteToken(token);
        }
    }
}
